package servlet;

import dao.Dao;
import domain.Administrators;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        String requestUrl = (String) session.getAttribute("requestUrl");
        Map<String, String[]> parameterMap = request.getParameterMap();
        Dao dao = new Dao();
        if (requestUrl.contains("user")) {
            User user = new User();
            try {
                BeanUtils.populate(user, parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            int i = dao.register_User(user);
            if (i > 0) {
                response.sendRedirect(request.getContextPath() + "/userLogin.jsp");
            } else {
                request.setAttribute("register_message", "注册用户失败，请重试");
                request.getRequestDispatcher("/userRegister.jsp").forward(request, response);
            }

        } else if (!requestUrl.contains("user")) {
            Administrators administrators = new Administrators();
            try {
                BeanUtils.populate(administrators, parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            int j = dao.register_Administrators(administrators);
            if (j > 0) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } else {
                request.setAttribute("register_message", "注册用户失败，请重试");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
